/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.cbm.randomprogram;

import com.elcom.emocbc.broadcastscheduler.dao.ConnectionProviderManager;
import com.elcom.emocbc.broadcastscheduler.dao.ScheduleRebuildCommandDao;
import com.elcom.emocbc.broadcastscheduler.entity.ScheduleRebuildCommand;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class ScheduleRebuildCommandChecker implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(ScheduleRebuild.class);

    @Override
    public void run() {
        try {
            logger.debug("Checking for pending ScheduleRebuildCommand");
            ScheduleRebuildCommandDao commandDao = new ScheduleRebuildCommandDao(ConnectionProviderManager.getInstance().getConnectionProvider());
            List<ScheduleRebuildCommand> pendingImmediateCommands = commandDao.findPendingImmediateCommands();
            if (pendingImmediateCommands != null && pendingImmediateCommands.size() > 0) {
                logger.debug("Found {} ScheduleRebuildCommand found", pendingImmediateCommands.size());
                ScheduleRebuild scheduleRebuild = new ScheduleRebuild();
                new Thread(scheduleRebuild).start();
                for (ScheduleRebuildCommand scheduleRebuildCommand : pendingImmediateCommands) {
                    commandDao.deleteByCommandId(scheduleRebuildCommand.getCommandId());
                }
                logger.debug("Deleted all pending ScheduleRebuildCommand");
            } else {
                logger.debug("No pending ScheduleRebuildCommand found");
            }

        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

}
